package com.coder.service;


import java.util.Date;

import com.coder.dao.UserDao;
import com.coder.model.User;
import com.coder.utils.MD5Util;
import com.coder.utils.MailUtil;

public class UserService {
	
	private UserDao userDao = null;
	
	public User getUserByName(String name){
		User user = null;
		user = userDao.getUserByPara("username",name);
		return user;
	}
	
	//保存用户
	public User saveOrUpdateUser(User userPa){
		User user = null;
		String validCode = MD5Util.encode2hex(userPa.getEmail());
		userPa.setRegisterDate(new Date());
		userPa.setValidCode(validCode);
		userPa.setIsDeleted(false);
		user = userDao.saveOrUpdate(userPa);
		return user;
	}


	public boolean checkUserExist(User user) {
		boolean exist = userDao.checkUserExist(user);
		return exist;
	}
	
	
	//给用户发送找回密码的邮件
	public User updateAndSendEmail4FindPw(String email) {
		User user = null;
		user = userDao.getUserByPara("email",email);

		long nowTime = System.currentTimeMillis();
		String validCode = MD5Util.encode2hex(email+nowTime);
		
		user.setValidCode(validCode);
		user.setValidDate(new Date());
		
		user = userDao.saveOrUpdate(user);
		
		StringBuffer sb = new StringBuffer("点击下面链接修改密码，12小时内有效，请尽快激活！<br>");
		sb.append("<a href=\"http://114.212.87.169:8080/bluebox/pwEmail?user.email=")
			.append(email)
			.append("&validateCode=")
			.append(validCode)
			.append("\">http://114.212.87.169:8080/bluebox/pwEmail?user.email=")
			.append(email)
			.append("&validateCode=")
			.append(validCode)
			.append("</a>");
		MailUtil.send(email , sb.toString());
		return user;
	}

	public User getUserByEmail(String email) { 
		User user = null;
		user = userDao.getUserByPara("email",email);
		return user;
	}
	
	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
 
	public void updateUser(User user) {
		userDao.saveOrUpdate(user);
	}
}
